#####################################################################
# $Id: DB.pm,v 1.1.1.1 2006/03/20 04:08:45 jfb Exp $
#
# DB.pm - Epiphyte database driver
#
#####################################################################

package Epiphyte::DB;

use strict;
use vars qw(@ISA $DBH);

use DBI;

use Epiphyte;
use Epiphyte::Log;

$DBH = undef;


#####################################################################
# open - class method
#
# Open a handle to the Epiphyte database specified as argument.
#####################################################################

sub open
{
	my ($class) = @_;

	my $spec = Epiphyte->getvar('DBSPEC');
	my $type = Epiphyte->getvar('DBDRIVER');
	$type = 'sql' if (!$type);

	if ($type eq 'csv') {
	}

	Epiphyte->log(LOG_INFO, "opening database connection");
	$DBH = DBI->connect("DBI:$spec");
	if (!$DBH) {
		Epiphyte->log(LOG_ERR, "failed to open database $spec: ",
		    DBI->errstr());
		return;
	}

	return (1);
}

#####################################################################
# close - object method
#
# Close a handle to the Epiphyte database specified as argument.
#####################################################################

sub close
{
	Epiphyte->log(LOG_INFO, "closing database connection");
	$DBH->disconnect();
}

#####################################################################
# create - class method
#
# Create the Epiphyte database and all tables.
#####################################################################

my %canopy_tables = (
	'users'		=> 'id INTEGER, name CHAR(32), passwd CHAR(32)',
	'forums'	=> 'id INTEGER, name CHAR(32)',
	'threads'	=> 'id INTEGER, title CHAR(128)',
	'posts'		=> 'id INTEGER, subject CHAR(128)',
);

sub create
{
	my ($class) = @_;

	foreach (keys(%canopy_tables)) {
		my $def = $canopy_tables{$_};
		Epiphyte->log(LOG_INFO, "creating $_ database table");
		if (!$DBH->do("CREATE TABLE $_ ($def)")) {
			Epiphyte->log(LOG_ERR, "failed to create $_ DB table: ",
			    $DBH->errstr());
			return;
		}
	}

}

1;
